package com.dataex.service;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.dataex.util.DBConnectionRegister;

public class XmlToDBService {

	public void importDataIntoDB(String path, String dbName) throws Exception {
		// sql
		String sql = "insert into users (userid,username,password) values(?,?,?)";
		// 调用工具包里的数据库连接方法
		Connection connection = DBConnectionRegister.getConnection();
		// 执行sql
		PreparedStatement presta = connection.prepareStatement(sql);
		// 定义解析器
		SAXReader reader = new SAXReader();
		// 获取文档对象
		Document document = reader.read(new File(path));
		// 获取根元素
		Element root = document.getRootElement();
		// 获取根元素下的用户集合
		List userList = root.elements();
		// 双重循环遍历每一个用户下的子元素信息
		for (int i = 0; i < userList.size(); i++) {
			Element userElement = (Element) userList.get(i);
			List itemList = userElement.elements();
			System.out.println("第" + (i + 1) + "个用户包含子元素个数：" + itemList.size());
			// 遍历每个用户的子元素信息
			for (int j = 0; j < itemList.size(); j++) {
				Element element = (Element) itemList.get(j);
				// 获取子元素信息进行参数设置
				presta.setString(j + 1, element.getText());
			}
			// 批量更新
			presta.addBatch();
			presta.executeBatch();
		}
		System.out.println("xml消息插入数据库成功！");
		// new DBConnectionUtil().close();
	}

	public static void readFile(int lineNumber) throws Exception {

		FileReader in = new FileReader(new File("D:/output/gxpt_czrk_photo.txt"));
		LineNumberReader reader = new LineNumberReader(in);
		String s = "";
		if (lineNumber <= 0 || lineNumber > getTotalLines(new File("D:/output/gxpt_czrk_photo.txt"))) {
			System.out.println("不在文件的行数范围(1至总行数)之内。");
			System.exit(0);
		}
		int lines = 0;
		while (s != null) {
			lines++;
			s = reader.readLine();
			System.out.println(s);
			if ((lines - lineNumber) == 0) {
				System.exit(0);
			}
		}
		reader.close();
		in.close();

	}

	// 文件内容的总行数。
	static int getTotalLines(File file) throws IOException {
		FileReader in = new FileReader(file);
		LineNumberReader reader = new LineNumberReader(in);
		String s = reader.readLine();
		int lines = 0;
		while (s != null) {
			lines++;
			s = reader.readLine();
		}
		reader.close();
		in.close();
		return lines;
	}

	public static void main(String[] args) throws Exception {
		readFile(3);
	}
}
